package BlogMybatis.blog.controller;


import BlogMybatis.blog.dto.AccessTokenDTO;
import BlogMybatis.blog.dto.GitHubUserDTO;
import BlogMybatis.blog.pojo.Githubuser;
import BlogMybatis.blog.provider.GitHubProvider;
import BlogMybatis.blog.service.GithubuserService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Date;


/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author Brandt
 * @since 2020-06-16
 */
@Controller

public class GithubuserController {

    @Autowired
    private GitHubProvider gitHubProvider;
    @Autowired
    private GithubuserService githubuserService;

    @Value("${github.client.id}")
    private String clientId;
    @Value("${github.client.secret}")
    private String clientSecret;
    @Value("${github.redirect.uri}")
    private String redirectUri;
    @Value("${cookie.time}")
    private Integer time;

    //回调地址
    @RequestMapping("/github/callback")
    public String callback(@RequestParam(name="code") String code,
                           @RequestParam(name="state") String state,
                           HttpServletRequest request,
                           HttpServletResponse response) throws Exception{
        AccessTokenDTO accessTokenDTO = new AccessTokenDTO();
        accessTokenDTO.setClient_id(clientId);
        accessTokenDTO.setClient_secret(clientSecret);
        accessTokenDTO.setCode(code);
        accessTokenDTO.setRedirect_uri(redirectUri);
        accessTokenDTO.setState(state);

        if(!StringUtils.isEmpty(code) && !StringUtils.isEmpty(state)){
            HttpSession session = request.getSession();
            //解决关闭浏览器就退出登录的bug
            Cookie cookie = new Cookie("JSESSIONID", session.getId());
            cookie.setPath(request.getContextPath() + "/");
            //设置cookie过期时间为两天
            cookie.setMaxAge(time);
            response.addCookie(cookie);

            String accessToken = gitHubProvider.getAccessToken(accessTokenDTO);
            GitHubUserDTO user = gitHubProvider.getUser(accessToken);

            session.setAttribute("node_id",user.getNode_id()); //GitHub用户唯一标识
            session.setAttribute("nickname",user.getName());  //GitHub用户名称
            session.setAttribute("avatar",user.getAvatar_url());  //GitHub用户头像
            session.setAttribute("loginStatus","true"); //登录状态
            session.setAttribute("loginType",2); //登录方式：1 QQ，2 GitHub

            QueryWrapper<Githubuser> wrapper = new QueryWrapper<>();
            wrapper.eq("node_id",user.getNode_id());
            Githubuser githubuser = githubuserService.getOne(wrapper, false);

            //如果为空，说明第一次登录，存进数据库
            if(githubuser == null){
                Githubuser gitHub = new Githubuser();
                gitHub.setAvatar(user.getAvatar_url());
                gitHub.setGithubId(String.valueOf(user.getId()));
                gitHub.setNodeId(user.getNode_id());
                gitHub.setCreatedTime(user.getCreated_at());
                gitHub.setUpdatedTime(user.getUpdated_at());
                gitHub.setNickname(user.getName());
                gitHub.setIndexUrl(user.getHtml_url());
                gitHub.setReceivedEventsUrl(user.getReceived_events_url());
                gitHub.setPublicRepos(user.getPublic_repos());
                gitHub.setSubscriptions(user.getSubscriptions_url());
                gitHub.setLoginTime(new Date().toString());
                githubuserService.save(gitHub);
            }
            //登录成功跳转到用户信息页
            return "redirect:/githubInfo";
        }
        //登录失败返回首页
        return "redirect:/index";
    }

    //GitHub用户信息页
    @GetMapping("/githubInfo")
    public String github(HttpSession session, Model model){
        String node_id = (String) session.getAttribute("node_id");
        QueryWrapper<Githubuser> wrapper = new QueryWrapper<>();
        wrapper.eq("node_id",node_id);
        Githubuser githubuser = githubuserService.getOne(wrapper);
        model.addAttribute("avatar",githubuser.getAvatar());
        model.addAttribute("github",githubuser);
        return "githubInfo";
    }

    //前端ajax提交请求到后端，保存登陆地等信息到数据库
    @PostMapping("/saveIp")
    public String postIp(HttpSession session){
        String node_id = (String) session.getAttribute("node_id");
        QueryWrapper<Githubuser> wrapper = new QueryWrapper<>();
        wrapper.eq("node_id",node_id);
        Githubuser gitHubuser = githubuserService.getOne(wrapper);
        if(gitHubuser.getCip() == null){  //ip信息为空，第一次登录，将前端传来ip信息存入数据库
            githubuserService.addIpAddress(node_id);
        }
        return "githubInfo";
    }

    //退出GitHub登录
    @GetMapping("/githublogout")
    public String logout(HttpSession session){
        //退出登录，将user中的信息清除
        session.removeAttribute("loginStatus");
        session.removeAttribute("avatar");
        session.removeAttribute("nickname");
        session.removeAttribute("node_id");
        session.removeAttribute("loginType");
        return "redirect:/index";
    }

}

